// player.js
const app = getApp();
const storage = require('../../utils/storage.js');

Page({
  data: {
    currentMusic: null,
    isPlaying: false,
    currentTime: '00:00',
    duration: '00:00',
    percent: 0,
    isFavorite: false,
    playMode: 'loop', // loop: 列表循环, random: 随机播放, single: 单曲循环
    showPlaylist: false,
    playlist: []
  },

  onLoad() {
    this.initPlayer();
  },

  onShow() {
    this.updatePlayerStatus();
  },

  onUnload() {
    // 页面卸载时保持音乐播放
  },

  // 初始化播放器
  initPlayer() {
    const audioManager = app.globalData.audioManager;
    
    // 监听播放
    audioManager.onPlay(() => {
      this.setData({ isPlaying: true });
    });
    
    // 监听暂停
    audioManager.onPause(() => {
      this.setData({ isPlaying: false });
    });
    
    // 监听停止
    audioManager.onStop(() => {
      this.setData({ isPlaying: false });
    });
    
    // 监听播放进度
    audioManager.onTimeUpdate(() => {
      const currentTime = this.formatTime(audioManager.currentTime || 0);
      const duration = this.formatTime(audioManager.duration || 0);
      const percent = audioManager.duration > 0 
        ? (audioManager.currentTime / audioManager.duration) * 100 
        : 0;
      
      this.setData({
        currentTime,
        duration,
        percent
      });
    });
    
    // 监听播放结束
    audioManager.onEnded(() => {
      this.handlePlayEnd();
    });
    
    // 监听错误
    audioManager.onError((err) => {
      console.error('播放错误', err);
      wx.showToast({
        title: '播放失败',
        icon: 'none'
      });
    });
    
    this.updatePlayerStatus();
  },

  // 更新播放器状态
  updatePlayerStatus() {
    const currentMusic = app.globalData.currentMusic;
    const audioManager = app.globalData.audioManager;
    const playlist = app.globalData.playlist || [];
    
    if (currentMusic) {
      const isFavorite = storage.isFavorite(currentMusic.id);
      
      this.setData({
        currentMusic,
        isPlaying: !audioManager.paused,
        isFavorite,
        playlist
      });
    }
  },

  // 格式化时间
  formatTime(seconds) {
    const min = Math.floor(seconds / 60);
    const sec = Math.floor(seconds % 60);
    return `${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`;
  },

  // 播放/暂停
  togglePlay() {
    const audioManager = app.globalData.audioManager;
    
    if (this.data.isPlaying) {
      audioManager.pause();
    } else {
      audioManager.play();
    }
  },

  // 上一首
  playPrev() {
    const playlist = app.globalData.playlist;
    const currentIndex = app.globalData.playIndex;
    
    if (!playlist || playlist.length === 0) return;
    
    let prevIndex;
    if (this.data.playMode === 'random') {
      prevIndex = Math.floor(Math.random() * playlist.length);
    } else {
      prevIndex = currentIndex === 0 ? playlist.length - 1 : currentIndex - 1;
    }
    
    this.playMusicAtIndex(prevIndex);
  },

  // 下一首
  playNext() {
    const playlist = app.globalData.playlist;
    const currentIndex = app.globalData.playIndex;
    
    if (!playlist || playlist.length === 0) return;
    
    let nextIndex;
    if (this.data.playMode === 'random') {
      nextIndex = Math.floor(Math.random() * playlist.length);
    } else {
      nextIndex = (currentIndex + 1) % playlist.length;
    }
    
    this.playMusicAtIndex(nextIndex);
  },

  // 播放指定索引的音乐
  playMusicAtIndex(index) {
    const playlist = app.globalData.playlist;
    const music = playlist[index];
    
    if (!music) return;
    
    app.globalData.currentMusic = music;
    app.globalData.playIndex = index;
    
    storage.addPlayHistory(music);
    
    const audioManager = app.globalData.audioManager;
    audioManager.title = music.title;
    audioManager.singer = music.singer;
    audioManager.coverImgUrl = music.coverImgUrl;
    audioManager.src = music.src;
    
    const isFavorite = storage.isFavorite(music.id);
    
    this.setData({
      currentMusic: music,
      isPlaying: true,
      isFavorite
    });
  },

  // 处理播放结束
  handlePlayEnd() {
    if (this.data.playMode === 'single') {
      // 单曲循环
      const audioManager = app.globalData.audioManager;
      audioManager.seek(0);
      audioManager.play();
    } else {
      // 播放下一首
      this.playNext();
    }
  },

  // 切换播放模式
  togglePlayMode() {
    const modes = ['loop', 'random', 'single'];
    const currentModeIndex = modes.indexOf(this.data.playMode);
    const nextMode = modes[(currentModeIndex + 1) % modes.length];
    
    this.setData({ playMode: nextMode });
    
    const modeNames = {
      'loop': '列表循环',
      'random': '随机播放',
      'single': '单曲循环'
    };
    
    wx.showToast({
      title: modeNames[nextMode],
      icon: 'none'
    });
  },

  // 收藏/取消收藏
  toggleFavorite() {
    if (!this.data.currentMusic) return;
    
    const isFavorite = this.data.isFavorite;
    
    if (isFavorite) {
      storage.removeFavorite(this.data.currentMusic.id);
      wx.showToast({
        title: '已取消收藏',
        icon: 'none'
      });
    } else {
      storage.addFavorite(this.data.currentMusic);
      wx.showToast({
        title: '已收藏',
        icon: 'success'
      });
    }
    
    this.setData({ isFavorite: !isFavorite });
  },

  // 进度条拖动
  onSliderChange(e) {
    const percent = e.detail.value;
    const audioManager = app.globalData.audioManager;
    const duration = audioManager.duration;
    
    if (duration > 0) {
      const currentTime = (percent / 100) * duration;
      audioManager.seek(currentTime);
    }
  },

  // 显示/隐藏播放列表
  togglePlaylist() {
    this.setData({
      showPlaylist: !this.data.showPlaylist
    });
  },

  // 从播放列表选择歌曲
  selectMusic(e) {
    const index = e.currentTarget.dataset.index;
    this.playMusicAtIndex(index);
    this.setData({ showPlaylist: false });
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  }
});
